﻿using IcsSEMCtrl.Global.Device;
using IcsSEMCtrl.Service.Logger;
using IcsSEMCtrl.Service.Material;
using IcsSEMCtrl.Util.Client;
using Lifter.Device;
using Lifter.Device.Dispatcher;
using Lifter.Gui.Monitor.Popups;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TKT.Lifter.CIM.Lifter.Global;
using TKT.Lifter.CIM.Lifter.Gui.Monitor.Popups;

namespace TKT.Lifter.CIM.Lifter.Gui.Monitor.Panels
{
    public partial class MaterialInfoControl : UserControl
    {
        private LifterSEM lftSem = null;
        public static MaterialInfoControl materialInfoControl = null;
        private delegate void delegateUpdateMaterial();
        private string selectMaterialID;//界面选中的物料ID

        public string SelectMaterialID { get => selectMaterialID; set => selectMaterialID = value; }

        public MaterialInfoControl()
        {
            InitializeComponent();
            materialInfoControl = this;
            this.InitializeMaterialDataGrid();
/*            if (this.lftSem == null)
            {
                this.lftSem = (LifterSEM)Naming.GetDeviceManager().GetDevice();
            }*/
        }
		private void InitializeMaterialDataGrid()
		{
			try
			{
				this.dgvMaterialInfo.AllowUserToAddRows = false;
				this.dgvMaterialInfo.Columns.Add(new DataGridViewTextBoxColumn());
				this.dgvMaterialInfo.Columns.Add(new DataGridViewTextBoxColumn());
				this.dgvMaterialInfo.Columns.Add(new DataGridViewTextBoxColumn());
				this.dgvMaterialInfo.Columns.Add(new DataGridViewTextBoxColumn());
				this.dgvMaterialInfo.Columns.Add(new DataGridViewTextBoxColumn());
                this.dgvMaterialInfo.Columns.Add(new DataGridViewTextBoxColumn());
                this.dgvMaterialInfo.Columns.Add(new DataGridViewTextBoxColumn());
                this.dgvMaterialInfo.Columns.Add(new DataGridViewTextBoxColumn());
                this.dgvMaterialInfo.Columns.Add(new DataGridViewTextBoxColumn());
                this.dgvMaterialInfo.Columns[0].HeaderText = "物料ID";
				this.dgvMaterialInfo.Columns[1].HeaderText = "物料位置";
				this.dgvMaterialInfo.Columns[2].HeaderText = "指令ID";
				this.dgvMaterialInfo.Columns[3].HeaderText = "物料类型";
				this.dgvMaterialInfo.Columns[4].HeaderText = "物料状态";
                this.dgvMaterialInfo.Columns[5].HeaderText = "读码状态";
                this.dgvMaterialInfo.Columns[6].HeaderText = "创建类型";
                this.dgvMaterialInfo.Columns[7].HeaderText = "创建时间";
                this.dgvMaterialInfo.Columns[8].HeaderText = "更新时间";

                this.dgvMaterialInfo.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
			}
			catch (Exception)
			{
			}
            this.UpdateMaterialForm();
		}
        public void UpdateDelegate()
        {
            base.BeginInvoke(new MaterialInfoControl.delegateUpdateMaterial(this.UpdateMaterialForm));
        }
        /// <summary>
        /// 更新物料信息表格数据
        /// add by yangshl
        /// </summary>
        public void UpdateMaterialForm()
        {
            try
            {
                this.dgvMaterialInfo.Rows.Clear();
                int index = 0;
                List<Carrier> carriers = new List<Carrier>();
                CarrierManager carrierManager = Naming.GetCarrierManager();
                lock (carrierManager.Collection_Monitor)
                {
                    foreach (Carrier carrier in carrierManager.carriers.Values)
                    {
                        carriers.Add(carrier);
                    }
                }
                if (carriers != null && carriers.Count() > 0)
                {
                    this.dgvMaterialInfo.RowCount = carriers.Count();
                    foreach (Carrier carrier in carriers)
                    {
                        this.dgvMaterialInfo.Rows[index].Cells[0].Value = carrier.CarrierId;
                        this.dgvMaterialInfo.Rows[index].Cells[1].Value = carrier.CarrierLoc;
                        this.dgvMaterialInfo.Rows[index].Cells[2].Value = carrier.CommandID;
                        this.dgvMaterialInfo.Rows[index].Cells[3].Value = carrier.CarrierType;
                        this.dgvMaterialInfo.Rows[index].Cells[4].Value = carrier.CarrierState;
                        this.dgvMaterialInfo.Rows[index].Cells[5].Value = carrier.IdReadState;
                        this.dgvMaterialInfo.Rows[index].Cells[6].Value = carrier.CreateType;
                        this.dgvMaterialInfo.Rows[index].Cells[7].Value = carrier.InstallTime;
                        this.dgvMaterialInfo.Rows[index].Cells[8].Value = carrier.UpdateTime;
                        if (carrier.OutputBCRReadMismatchFlag)
                        {
                            this.dgvMaterialInfo.Rows[index].DefaultCellStyle.BackColor = Color.Red;
                        }
                        index++;
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.loggerError("在[UpdateMaterialForm]方法中失败", ex);
            }
        }

        private void btMaterialAdd_Click(object sender, EventArgs e)
        {
            this.lftSem = (LifterSEM)Naming.GetDeviceManager().GetDevice();
            if (!this.lftSem.UserPrivilige)
            {
                PopupNotice.DialogPopups("请先登录", "Please login", enumPopupsType.Warning);
            }
            else
            {
                if (this.lftSem.UserPrivilige)
                {
                    this.lftSem.LoginTimeCount = 1;
                }
                MaterialAdd materialAdd = new MaterialAdd();
                materialAdd.ShowDialogWithMask();
                if (materialAdd.IsOK)
                {
                    materialAdd.CreateManualMaterial();
                }
                materialAdd.Dispose();
            }
        }

        private void bt_MaterialUpdate_Click(object sender, EventArgs e)
        {
            this.lftSem = (LifterSEM)Naming.GetDeviceManager().GetDevice();
            if (!this.lftSem.UserPrivilige)
            {
                PopupNotice.DialogPopups("请先登录", "Please login", enumPopupsType.Warning);
            }
            else
            {
                if (this.lftSem.UserPrivilige)
                {
                    this.lftSem.LoginTimeCount = 1;
                }
                MaterialEdit materialEdit = new MaterialEdit();
                if (!string.IsNullOrEmpty(this.selectMaterialID))
                {
                    Carrier carrier = this.lftSem.GetCarrierByCarrierID(selectMaterialID);
                    if (carrier != null)
                    {
                        materialEdit.cbCommandID.Text = carrier.CommandID;
                        materialEdit.cbMaterialID.Text = carrier.CarrierId;
                        materialEdit.cbMaterialLocal.Text = carrier.CarrierLoc;
                        materialEdit.cbMaterialType.Text = CarrierType.ValueToString(carrier.CarrierType);
                        materialEdit.cbStatus.Text = CarrierState.ValueToString(carrier.CarrierState);
                    }
                }
                materialEdit.ShowDialogWithMask();
                if (materialEdit.IsOK)
                {
                    materialEdit.UpdateManualMaterial();
                }
                materialEdit.Dispose();
            }
        }

        private void btMaterialDelete_Click(object sender, EventArgs e)
        {
            this.lftSem = (LifterSEM)Naming.GetDeviceManager().GetDevice();
            if (!this.lftSem.UserPrivilige)
            {
                PopupNotice.DialogPopups("请先登录", "Please login", enumPopupsType.Warning);
            }
            else
            {
                Carrier carrier = this.lftSem.GetCarrierByCarrierID(this.selectMaterialID);
                if (carrier != null)
                {
                    carrier.CompleteResult = Carrier.MaterialCompleteTypeConstants.RESULT_NG_CANCEL;
                    Naming.GetCarrierManager().DeleteCarrier(carrier.CarrierId);
                    MaterialInfoControl.materialInfoControl.UpdateDelegate();
                    LogHelper.operationLogger(string.Format("用户[{0}]删除物料成功，物料ID为:[{1}]", this.lftSem.UserName, this.selectMaterialID));
                    lftSem.InsertUserOperation(lftSem.UserName, string.Format("用户[{0}]删除物料成功，物料ID为:[{1}]", this.lftSem.UserName, this.selectMaterialID));

                }
            }
        }

        private void dgvMaterialInfo_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            int index = e.RowIndex;
            try
            {
                if (this.dgvMaterialInfo.Rows[index].Cells[0].Value != null)
                {
                    this.selectMaterialID = this.dgvMaterialInfo.Rows[index].Cells[0].Value.ToString();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("选择的物料报错，在dgvTansferComandShow_SelectIndexChange方法中");
                LogHelper.loggerError("选择的物料报错，在dgvTansferComandShow_SelectIndexChange方法中", ex);
            }
        }

        private void btDeleteAllMaterial_Click(object sender, EventArgs e)
        {
            try
            {
                this.lftSem = (LifterSEM)Naming.GetDeviceManager().GetDevice();
                //判断用户是否登录
                if (this.lftSem.UserPrivilige)
                {
                    if (UIMessageDialog.ShowAskDialog(base.FindForm(), $"确认是否要全部删除物料！！！"))
                    {
                        List<string> materialIDs = new List<string>();
                        foreach (DataGridViewRow dataGridViewRow in this.dgvMaterialInfo.Rows)
                        {
                            materialIDs.Add(dataGridViewRow.Cells[0].Value.ToString());
                        }
                        foreach (string materialID in materialIDs)
                        {
                            Carrier carrier = this.lftSem.GetCarrierByCarrierID(materialID);
                            if (carrier != null)
                            {
                                carrier.CompleteResult = Carrier.MaterialCompleteTypeConstants.RESULT_NG_CANCEL;
                                Naming.GetCarrierManager().DeleteCarrier(carrier.CarrierId);
                                MaterialInfoControl.materialInfoControl.UpdateDelegate();
                                LogHelper.operationLogger(string.Format("用户[{0}]删除物料成功，物料ID为:[{1}]", this.lftSem.UserName, this.selectMaterialID));
                                lftSem.InsertUserOperation(lftSem.UserName, string.Format("用户[{0}]删除物料成功，物料ID为:[{1}]", this.lftSem.UserName, this.selectMaterialID));

                            }
                        }
                    }
                }
                else
                {
                    PopupNotice.DialogPopups("请先登录", "Please login", enumPopupsType.Warning);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("用户删除所有物料报错，在方法btDeleteAllMaterial_Click中");
                LogHelper.loggerError("用户删除所有物料报错，在方法btDeleteAllMaterial_Click中", ex);
                throw;
            }
        }
    }
}
